package com.lancoo.examview.test;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.eventBean.AudioUpLoadEventBean;
import com.lancoo.answer.model.eventBean.ImageEventBean;
import com.lancoo.answer.model.eventBean.SubmitEventBean;
import com.lancoo.examview.R;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.manager.TaskManager;
import com.lancoo.examview.test.presenter.PaperPresenter;
import com.lancoo.examview.utils.ConvertStremUtils;
import com.lancoo.examview.utils.FontSizeChangeUtils;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class PaperActivity extends AppCompatActivity {

    private static final String TAG = "PaperActivity";
    private PaperPresenter mPresenter;
    private TaskManager manager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paper);
        mPresenter = new PaperPresenter();
        EventBus.getDefault().register(this);

        Observable.create((ObservableOnSubscribe<List<Type>>) emitter -> {
                    List<Type> list;
                    String originalFundData = getOriginalFundData();
                    Gson gson = new Gson();
                    java.lang.reflect.Type listType = new TypeToken<ArrayList<Type>>() {
                    }.getType();
                    list = gson.fromJson(originalFundData, listType);
                    emitter.onNext(list);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(this::initView, throwable -> {});
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView(List<Type> typeList) {
        manager = new TaskManager();
        TaskControlBean taskControlBean = new TaskControlBean();
        int trainSence = getIntent().getIntExtra("trainSence", 0);
        taskControlBean.setTrainSence(trainSence);
////        taskControlBean.setExpired(true);
//        taskControlBean.setPaperType(0);
//        taskControlBean.setTrainSence(1);
        manager.loadTaskFragment(getSupportFragmentManager(), taskControlBean, typeList, R.id.framelayout);
    }

    private String getOriginalFundData() {
        InputStream inputStream;
        try {
            String dataAsset = getIntent().getStringExtra("dataAsset");
            inputStream = getAssets().open(dataAsset);
            String json = convertStremToString(inputStream);
            inputStream.close();
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("eee", "Exception" + e.toString());
        }
        return null;
    }

    private String convertStremToString(InputStream is) {
        String s = null;
        try {
            Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A");
            if (scanner.hasNext()) {
                s = scanner.next();
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 图片上传
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubmitEvent(final SubmitEventBean eventBean) {
        Single.timer(3000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        manager.closePaperAnswerSheetDialog(getSupportFragmentManager());
                    }
                });
    }

    /**
     * 图片上传
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImageEventUpLoad(final ImageEventBean imageEvent) {
        Log.e(TAG, new Gson().toJson(imageEvent));
        if (imageEvent.getOperateType() == 0) {
            mPresenter.uploadImages(imageEvent.getImgList(), imageEvent);
        }
    }

    /**
     * 音频上传
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioEventUpLoad(final AudioUpLoadEventBean eventBean) {
        Log.e(TAG, new Gson().toJson(eventBean));
        if (eventBean.getOperateType() == 0) {
            mPresenter.uploadAudioPath(eventBean);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_sheet, menu);
        return true;
    }


    private long time;

    @Override
    public boolean onOptionsItemSelected(@NotNull MenuItem item) {
        if (System.currentTimeMillis() - time < 500) {
            return false;
        }
        time = System.currentTimeMillis();
        if (item.getItemId() == R.id.menu_sheet) {
            if (manager != null) {
                manager.closeAllPaperAudioPlay(getSupportFragmentManager());
                manager.showPaperAnswerSheetDialog(getSupportFragmentManager());
            }
        }else if(item.getItemId()==R.id.menu_font){
            FontSizeChangeUtils.showFontSizeChangeAlertDialog(this, new FontSizeChangeUtils.FontSizeChangeCallBack() {
                @Override
                public void upDateAllFontSize(int fontIndex, int textSize, int TextZoom) {


                }

                @Override
                public void upDateFontSize(int fontIndex, int textSize, int textZoom) {
                    Log.e("evlog","upDateFontSize:"+fontIndex);
                    if(manager!=null){
                        manager.adjustFontSize(getSupportFragmentManager());
                    }
                }
            });
        }
        return super.onOptionsItemSelected(item);
    }

    public static void launch(Context mContext, String dataAsset, TaskState taskState) {
        ConstantBean.setTaskState(taskState);
        Intent mIntent = new Intent(mContext, PaperActivity.class);
        mIntent.putExtra("dataAsset", dataAsset);
        mContext.startActivity(mIntent);
    }

    public static void launch(Context mContext, String dataAsset, TaskState taskState, int trainSence) {
        ConstantBean.setTaskState(taskState);
        Intent mIntent = new Intent(mContext, PaperActivity.class);
        mIntent.putExtra("dataAsset", dataAsset);
        mIntent.putExtra("trainSence", trainSence);
        mContext.startActivity(mIntent);
    }

}